<?php
namespace App\Module\User\Service;

use App\Common\Service\SmsService;
use App\Constants\Constant;
use App\Exception\AppException;
use App\Model\Child;
use App\Model\ChildUserMid;
use App\Module\User\Request\Child\BindRequest;
use App\Module\User\Request\Child\UpdateRequest;
use Hyperf\Di\Annotation\Inject;
use Qbhy\HyperfAuth\AuthManager;

class ChildService {

    /**
     * @Inject()
     * @var AuthManager $authManager
     */
    private $authManager;

    /**
     * @Inject()
     * @var SmsService $smsService
     */
    private $smsService;

    public function search($pagesize){
        return $this->authManager->guard(Constant::USER)->user()->childs()->with("family")->paginate($pagesize);
    }

    public function unbind($id){
        return ChildUserMid::query()->where([['user_id',$this->authManager->guard(Constant::USER)->user()->getId()],['child_id',$id]])->delete();
    }

    public function getById($id){
        return $this->authManager->guard(Constant::USER)->user()->childs()->find($id);
    }

    public function update(UpdateRequest $request,$id){
        $model = $this->authManager->guard(Constant::USER)->user()->childs()->findOrFail($id);
        $model->fill($request->all());
        return $model->save();
    }

    public function bind(BindRequest $request){

        $child = Child::query()->where([['name',$request->input("child_name")],['parent_mobile',$request->input("parent_mobile")]])->first();
        if(!$child){
            throw new AppException("您的信息错误,请确认后重试");
        }

        if(!$this->smsService->verify($child->getAttribute("parent_mobile"),$request->input("code"))){
            throw new AppException("验证码不正确");
        }

        return ChildUserMid::query()->insertOrIgnore([
            'child_id'=>$child->child_id,
            'user_id'=>$this->authManager->guard(Constant::USER)->user()->getId(),
            'nickname'=>$request->input("nickname"),
            'thumbnail'=>$this->authManager->guard(Constant::USER)->user()->thumbnail
        ]);
    }
}